<template>
  <el-drawer
    custom-class="select-parent"
    title="分配角色权限"
    size="450px"
    :wrapperClosable="false"
    :append-to-body="true"
    :before-close="beforeClose"
    :visible.sync="show"
  >
    <div class="select-parent__content">
      <el-tree
        ref="treeRef"
        show-checkbox
        :indent="24"
        :default-checked-keys="defaultCheckedKeys"
        node-key="menuId"
        :data="treeData"
        default-expand-all
        :props="{
          children: 'children',
          label: 'title'
        }"
        :expand-on-click-node="false"
      ></el-tree>
    </div>

    <div class="footer">
      <el-button type="danger" @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确认</el-button>
    </div>
  </el-drawer>
</template>

<script>
import { assignRoleMenuApi } from '@/api/role'
export default {
  props: {
    show: {
      type: Boolean,
      default: false
    },
    selectRow: {
      type: Object,
      default: () => ({})
    },
    treeData: {
      type: Array,
      default: () => []
    },
    defaultCheckedKeys: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    defaultCheckedKeys(value) {
      this.$nextTick(() => {
        if (this.$refs.treeRef) {
          this.$refs.treeRef.setCheckedKeys(value)
        }
      })
    }
  },
  methods: {
    beforeClose() {
      this.$emit('update:show', false)
    },
    handleCancel() {
      this.$emit('update:show', false)
    },
    async handleConfirm() {
      let parentList = this.$refs.treeRef.getHalfCheckedKeys()
      let childList = this.$refs.treeRef.getCheckedKeys()
      let res = await assignRoleMenuApi({
        roleId: this.selectRow.roleId,
        menuIdList: [...parentList, ...childList]
      })
      if (res.success) {
        this.$message.success('分配权限成功！')
        this.$emit('update:show', false)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
  border-top: 1px solid #eee;
  text-align: right;
  padding: 20px;
}
::v-deep .select-parent {
  .el-drawer__header {
    color: #333;
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
  }
  .select-parent__content {
    padding: 15px;
    border-top: 1px solid #eee;
  }

  .el-tree-node__content {
    height: 30px;
    .el-tree-node__label {
      display: inline-block;
      font-size: 16px;
      line-height: 30px;
      color: #333;
    }
  }
}
</style>
